import React, { useState, useCallback, useMemo } from "react";
import Icon, { Icons, icons } from "../utils/icons";
import { message } from "antd";

const SimpleIconDemo: React.FC = () => {
  const [size, setSize] = useState(24);
  const [color, setColor] = useState("#333333");
  const [searchTerm, setSearchTerm] = useState("");
  const [copySuccess, setCopySuccess] = useState<string | null>(null);
  const [messageApi, contextHolder] = message.useMessage();

  // 获取所有可用的图标名称
  const allIconNames = Object.keys(icons);

  // 构建所有可用的Icons组件
  const directIcons = Object.entries(Icons);

  // 根据搜索词过滤图标
  const filteredDirectIcons = useMemo(() => {
    if (!searchTerm.trim()) return directIcons;
    const term = searchTerm.toLowerCase();
    return directIcons.filter(([name]) => name.toLowerCase().includes(term));
  }, [directIcons, searchTerm]);

  const filteredIconNames = useMemo(() => {
    if (!searchTerm.trim()) return allIconNames;
    const term = searchTerm.toLowerCase();
    return allIconNames.filter((name) => name.toLowerCase().includes(term));
  }, [allIconNames, searchTerm]);

  // 改进的复制到剪贴板函数
  const copyToClipboard = useCallback(
    (text: string, iconName: string) => {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          // 设置状态以显示动画效果
          setCopySuccess(iconName);
          setTimeout(() => setCopySuccess(null), 1500);

          // 显示全局成功消息
          messageApi.success({
            content: `已复制 "${iconName}" 图标代码到剪贴板`,
            duration: 2,
          });
        })
        .catch((err) => {
          console.error("复制失败:", err);
          messageApi.error("复制失败，请手动复制");
        });
    },
    [messageApi]
  );

  // 复制导入语句
  const copyImport = useCallback(
    (iconName: string) => {
      const importText = `import { Icons } from '@/utils/icons';\n\n<Icons.${iconName} size={${size}} fill="${color}" />`;
      copyToClipboard(importText, iconName);
    },
    [copyToClipboard, size, color]
  );

  // 复制统一组件语句
  const copyUnified = useCallback(
    (iconName: string) => {
      const importText = `import Icon from '@/utils/icons';\n\n<Icon name="${iconName}" size={${size}} fill="${color}" />`;
      copyToClipboard(importText, iconName);
    },
    [copyToClipboard, size, color]
  );

  return (
    <div style={{ fontFamily: "Arial, sans-serif", padding: "20px" }}>
      {contextHolder}
      <h1 style={{ fontSize: "24px", marginBottom: "16px" }}>图标演示</h1>

      <div
        style={{
          marginBottom: "16px",
          display: "flex",
          gap: "20px",
          flexWrap: "wrap",
        }}
      >
        <div>
          <label style={{ marginRight: "8px" }}>图标大小:</label>
          <input
            type="range"
            min="12"
            max="48"
            value={size}
            onChange={(e) => setSize(Number(e.target.value))}
          />
          <span style={{ marginLeft: "8px" }}>{size}px</span>
        </div>

        <div>
          <label style={{ marginRight: "8px" }}>图标颜色:</label>
          <input
            type="color"
            value={color}
            onChange={(e) => setColor(e.target.value)}
          />
        </div>

        <div style={{ flexGrow: 1 }}>
          <label style={{ marginRight: "8px" }}>搜索图标:</label>
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="输入图标名称..."
            style={{
              padding: "6px 12px",
              borderRadius: "4px",
              border: "1px solid #ddd",
              minWidth: "240px",
            }}
          />
          {searchTerm && (
            <button
              onClick={() => setSearchTerm("")}
              style={{ marginLeft: "8px", padding: "6px 12px" }}
            >
              清除
            </button>
          )}
        </div>
      </div>

      <h2 style={{ fontSize: "18px", marginTop: "24px", marginBottom: "16px" }}>
        方式1: 从Icons导入组件 ({filteredDirectIcons.length}/
        {directIcons.length})
      </h2>
      <div
        style={{
          display: "flex",
          gap: "16px",
          marginBottom: "24px",
          flexWrap: "wrap",
        }}
      >
        {filteredDirectIcons.map(([name, Component]) => (
          <div
            key={name}
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              border: "1px solid #ddd",
              borderRadius: "8px",
              padding: "16px",
              width: "120px",
              marginBottom: "16px",
              cursor: "pointer",
              position: "relative",
              transition: "all 0.25s ease",
              boxShadow: "0 2px 4px rgba(0,0,0,0.05)",
              overflow: "hidden",
            }}
            onClick={() => copyImport(name)}
            title={`点击复制 ${name} 图标代码`}
            onMouseOver={(e) => {
              e.currentTarget.style.transform = "translateY(-3px)";
              e.currentTarget.style.boxShadow = "0 4px 8px rgba(0,0,0,0.1)";
            }}
            onMouseOut={(e) => {
              e.currentTarget.style.transform = "translateY(0)";
              e.currentTarget.style.boxShadow = "0 2px 4px rgba(0,0,0,0.05)";
            }}
          >
            <Component width={size} height={size} fill={color} />
            <span
              style={{
                marginTop: "12px",
                fontSize: "14px",
                color: "#555",
                textAlign: "center",
                wordBreak: "break-all",
              }}
            >
              {name}
            </span>
            {copySuccess === name && (
              <div
                style={{
                  position: "absolute",
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  backgroundColor: "rgba(0,0,0,0.7)",
                  color: "white",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  borderRadius: "8px",
                  fontWeight: "bold",
                  animation: "fadeIn 0.2s ease-in-out",
                }}
              >
                <div style={{ textAlign: "center" }}>
                  <div style={{ fontSize: "24px", marginBottom: "4px" }}>✓</div>
                  已复制!
                </div>
              </div>
            )}
          </div>
        ))}
        {filteredDirectIcons.length === 0 && (
          <div
            style={{
              padding: "20px",
              color: "#888",
              width: "100%",
              textAlign: "center",
            }}
          >
            没有找到匹配的图标
          </div>
        )}
      </div>

      <h2 style={{ fontSize: "18px", marginTop: "24px", marginBottom: "16px" }}>
        方式2: 使用统一Icon组件 ({filteredIconNames.length}/
        {allIconNames.length})
      </h2>
      <div style={{ display: "flex", gap: "16px", flexWrap: "wrap" }}>
        {filteredIconNames.map((iconName) => (
          <div
            key={iconName}
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              border: "1px solid #ddd",
              borderRadius: "8px",
              padding: "16px",
              width: "120px",
              marginBottom: "16px",
              cursor: "pointer",
              position: "relative",
              transition: "all 0.25s ease",
              boxShadow: "0 2px 4px rgba(0,0,0,0.05)",
            }}
            onClick={() => copyUnified(iconName)}
            title={`点击复制 ${iconName} 图标代码`}
            onMouseOver={(e) => {
              e.currentTarget.style.transform = "translateY(-3px)";
              e.currentTarget.style.boxShadow = "0 4px 8px rgba(0,0,0,0.1)";
            }}
            onMouseOut={(e) => {
              e.currentTarget.style.transform = "translateY(0)";
              e.currentTarget.style.boxShadow = "0 2px 4px rgba(0,0,0,0.05)";
            }}
          >
            <Icon name={iconName} size={size} fill={color} />
            <span
              style={{
                marginTop: "12px",
                fontSize: "14px",
                color: "#555",
                textAlign: "center",
                wordBreak: "break-all",
              }}
            >
              {iconName}
            </span>
            {copySuccess === iconName && (
              <div
                style={{
                  position: "absolute",
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  backgroundColor: "rgba(0,0,0,0.7)",
                  color: "white",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  borderRadius: "8px",
                  fontWeight: "bold",
                  animation: "fadeIn 0.2s ease-in-out",
                }}
              >
                <div style={{ textAlign: "center" }}>
                  <div style={{ fontSize: "24px", marginBottom: "4px" }}>✓</div>
                  已复制!
                </div>
              </div>
            )}
          </div>
        ))}
        {filteredIconNames.length === 0 && (
          <div
            style={{
              padding: "20px",
              color: "#888",
              width: "100%",
              textAlign: "center",
            }}
          >
            没有找到匹配的图标
          </div>
        )}
      </div>

      <div
        style={{
          marginTop: "32px",
          padding: "16px",
          backgroundColor: "#f5f5f5",
          borderRadius: "8px",
        }}
      >
        <h3 style={{ fontSize: "16px", marginTop: 0, marginBottom: "8px" }}>
          使用说明
        </h3>
        <p style={{ margin: "8px 0", color: "#666" }}>
          • 点击任意图标可以复制其导入代码
          <br />
          • 搜索框可以按名称过滤图标
          <br />• 调整大小和颜色可以预览不同样式
        </p>
        <pre
          style={{
            margin: 0,
            padding: "8px",
            backgroundColor: "#eee",
            overflow: "auto",
            borderRadius: "4px",
          }}
        >
          {`// 方式1: 从Icons导入
import { Icons } from '@/utils/icons';

<Icons.${
            allIconNames.length > 0 ? allIconNames[0] : "IconName"
          } size={${size}} fill="${color}" />

// 方式2: 使用统一组件
import Icon from '@/utils/icons';

<Icon name="${
            allIconNames.length > 0 ? allIconNames[0] : "iconName"
          }" size={${size}} fill="${color}" />`}
        </pre>
      </div>
      <style jsx>{`
        @keyframes fadeIn {
          0% {
            opacity: 0;
          }
          100% {
            opacity: 1;
          }
        }
      `}</style>
    </div>
  );
};

export default SimpleIconDemo;
